namespace mrs;

using System.ComponentModel;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
[ApiExplorerSettings(IgnoreApi = true)] 
public class WorkerController : ControllerBase
{
    private readonly ILogger<WorkerController> _logger;
    private static int _executionCount = 0;
    private static DateTime _startTime = DateTime.UtcNow;
    private static readonly List<string> _operationLogs = new();

    public WorkerController(ILogger<WorkerController> logger)
    {
        _logger = logger;
        _logger.LogInformation("WorkerController initialized");
    }

    [HttpGet("config")]
    public IActionResult GetConfiguration()
    {
        var config = new
        {
            environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production",
            machineName = Environment.MachineName,
            osVersion = Environment.OSVersion.ToString(),
            processId = System.Diagnostics.Process.GetCurrentProcess().Id,
            basePath = AppContext.BaseDirectory,
            runtimeVersion = Environment.Version.ToString()
        };

        return Ok(config);
    }

    [HttpGet("status")]
    public IActionResult GetWorkerStatus()
    {
        _executionCount++;
        var uptime = DateTime.UtcNow - _startTime;

        _logger.LogInformation("Meteor Worker status requested, execution count: {count}", _executionCount);

        return Ok(new
        {
            service = "Meteor Worker Service",
            status = "Running",
            uptime = $"{uptime.Days}d {uptime.Hours}h {uptime.Minutes}m {uptime.Seconds}s",
            executionCount = _executionCount,
            startTime = _startTime,
            currentTime = DateTime.UtcNow,
            totalLogs = _operationLogs.Count
        });
    }

    [HttpGet("performance")]
    public IActionResult GetPerformanceInfo()
    {
        var process = System.Diagnostics.Process.GetCurrentProcess();

        return Ok(new
        {
            memoryUsageMB = Math.Round(process.WorkingSet64 / 1024.0 / 1024.0, 2),
            privateMemoryMB = Math.Round(process.PrivateMemorySize64 / 1024.0 / 1024.0, 2),
            cpuTime = process.TotalProcessorTime.ToString(),
            threads = process.Threads.Count,
            startTime = process.StartTime,
            handleCount = process.HandleCount
        });
    }

    [HttpGet("logs")]
    public IActionResult GetOperationLogs()
    {
        return Ok(new
        {
            totalLogs = _operationLogs.Count,
            logs = _operationLogs
        });
    }

    // 下面都出错

    [HttpPost("restart")]
    public IActionResult SimulateRestart()
    {
        _executionCount = 0;
        _startTime = DateTime.UtcNow;
        _operationLogs.Clear();

        _logger.LogWarning("Worker service stats reset simulated");

        return Ok(new
        {
            message = "Moetor Worker statistics reset successfully",
            newStartTime = _startTime
        });
    }

    [HttpPost("log/test")]
    public IActionResult TestLogging([FromBody] LogRequest request)
    {
        // 405 Method Not Allowed
        var logLevel = request.Level?.ToUpper() ?? "INFO";
        var message = request.Message ?? "Test log message";
        var logEntry = $"{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} [{logLevel}] {message}";

        // 添加到操作日志
        _operationLogs.Add(logEntry);
        if (_operationLogs.Count > 50) // 只保留最近50条日志
        {
            _operationLogs.RemoveAt(0);
        }

        switch (logLevel)
        {
            case "ERROR":
                _logger.LogError("Test error log: {message}", message);
                break;
            case "WARNING":
                _logger.LogWarning("Test warning log: {message}", message);
                break;
            case "INFO":
                _logger.LogInformation("Test info log: {message}", message);
                break;
            case "DEBUG":
                _logger.LogDebug("Test debug log: {message}", message);
                break;
            default:
                _logger.LogInformation("Test log: {message}", message);
                break;
        }

        return Ok(new
        {
            logged = true,
            level = logLevel,
            message = message,
            timestamp = DateTime.UtcNow,
            logEntry = logEntry
        });
    }

    [HttpPost("execute")]
    public IActionResult ExecuteCommand([FromBody] CommandRequest request)
    {
        // 405 Method Not Allowed
        if (string.IsNullOrWhiteSpace(request.Command))
        {
            return BadRequest(new { error = "Command cannot be empty" });
        }

        var result = new
        {
            command = request.Command,
            executedAt = DateTime.UtcNow,
            status = "Completed",
            result = $"Command '{request.Command}' executed successfully"
        };

        _logger.LogInformation("Command executed: {command}", request.Command);

        // 记录到操作日志
        _operationLogs.Add($"{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} [COMMAND] {request.Command}");
        if (_operationLogs.Count > 50)
        {
            _operationLogs.RemoveAt(0);
        }

        return Ok(result);
    }

    [HttpDelete("logs/clear")]
    public IActionResult ClearLogs()
    {
        // 405 Method Not Allowed
        var count = _operationLogs.Count;
        _operationLogs.Clear();

        _logger.LogInformation("Cleared {count} operation logs", count);

        return Ok(new { clearedCount = count });
    }

    // {{END}}
}
